package com.jxb.demo.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;

public class NettyServer {

    /**
     * @desc nettyServer启动
     * @throws InterruptedException
     */
    public void start()throws InterruptedException{
        //创建boss及work线程组
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //boss处理客户端的连接，work处理与客户端的读写操作
        serverBootstrap.group(boss,work)
                //NIO类型的channel
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,100)
                //连接到达时，会创建一个通道
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //服务端解码
                        pipeline.addLast(new LengthFieldBasedFrameDecoder(65532,0,2,0,2));
                        pipeline.addLast(new MsgPackDecoder());
                        pipeline.addLast(new MsgPackEncoder());
                        pipeline.addLast(new LengthFieldPrepender(2));
                        pipeline.addLast(new NettyServerHandler());
                    }
                });
        //配置完成，绑定server，调用sync方法阻塞直到绑定成功
        ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
        //关闭通道
        channelFuture.channel().closeFuture().sync();
    }

    public static void main(String[] args) {
        try{
            new NettyServer().start();

        }catch (Exception e){

        }

    }

}
